<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 麦当苗儿 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use User\Api\UserApi as UserApi;
use Think\Model;

/**
 * 后台首页控制器
 * @author 麦当苗儿 <zuojiazi@vip.qq.com>
 */
class InventoryController extends AdminController {
    /***
     *实时库存列表
     */
    public function inventoryrealtime($BIN="",$pname="",$classify="",$cnt=0){
        $map = array();
        $where="";
        if($BIN!==""){
            $map['BIN'] = array('like','%'.I('BIN').'%');
            $where.=" and a.BIN like '%".$BIN."%'";
        }
        if($pname!==""){
            $map['pname'] = array('like','%'.I('pname').'%');
            $where.=" and a.pname like '%".$pname."%'";
        }
        if($classify!==""){
            $map['BIN'] = array('like',I('classify').'%');
            $where.=" and a.BIN like '".$classify."%'";
        }
//        $map['cnt']=array('gt',$cnt);
//        $where.=" and a.cnt>$cnt";
        $model = M('vinventory');
        $res = $model->where($map)->select();
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);

        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $classify = M('Material_classify')->where(array('status'=>1))->select();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql="select a.*,(select b.updateAt from gr_inventory_warn b where a.BIN=b.BIN ORDER by b.updateAt DESC limit 1) as updateAt,(select b.checkAt from gr_inventory_warn b where a.BIN=b.BIN ORDER by b.checkAt DESC limit 1) as pd from gr_vinventory a where 1=1 ".$where." order by a.cnt desc limit $page->firstRow,$page->listRows";
//        $res = $model->where($map)->limit($page->firstRow ,$page->listRows)->select();
        $hideArr=M('Inventory_hide')->getField('BIN',true);
        $this->assign('hidearr',$hideArr);
        $res = $model->query($sql);
        $this->assign("_list",$res);
        $this->assign("_classify",$classify);
        $this->classify=I('classify');
        $this->cnt=$cnt;
        $this->title = "实时库存";

        $this->display();
    }
    public function ybzinadd($BIN=array(),$cnt=array(),$have_days=array()){
        if(IS_POST){
            $model = M('Inventory_warn');
            $trans = true;
            for ($i = 0; $i < count($BIN); $i++) {
                if ($BIN[$i] == ""||$cnt[$i] == ""||$have_days[$i] == "") {
                    $this->error("入库商品信息不能为空");
                }
            }
            $model->startTrans();
            for ($i = 0; $i < count($BIN); $i++) {
                $fruit_classify_no = get_no_by_tag($BIN[$i],'fruit_classify_no');//获取水果分类编号
                $info = getperiod($fruit_classify_no);//获取水果分类的周期
//                $batchMap['warn_batch'] = $warn_batch[$i]?$warn_batch[$i]:$w;
                $d = $have_days[$i];
                if($d>=10){
                    $w = date("Ymd",time()).$d;
                }else{
                    $w = date("Ymd",time())."0".$d;
                }
                $batchMap['warn_batch'] = $w;
                $batchMap['BIN'] = $BIN[$i];
                if($model->where($batchMap)->find()){
                    if(!$model->where($batchMap)->setInc('cnt',$cnt[$i])){
                        $trans = false;
                    }else{
                        $model->where($batchMap)->save(array('updateAt'=>time()));
                    }
                }else{
                    $period2 =  date("Ymd",strtotime("+".($info['per2_time']-$have_days[$i])." day"));
                    $period3 =  date("Ymd",strtotime("+".($info['per3_time']-$have_days[$i])." day"));
                    $batchData['BIN']= $BIN[$i];
                    $batchData['warn_batch']= $w;
                    $batchData['cnt']= $cnt[$i];
                    $batchData['initcnt']= $cnt[$i];
                    $batchData['pname']= get_name_by_id($BIN[$i],'Material_product','BIN','pname');
                    $batchData['have_days']= $d;
                    $batchData['createDay']= date("Ymd",time());
                    $batchData['per2_time']= $period2;
                    $batchData['per3_time']= $period3;
                    $batchData['createAt']= time();
                    $batchData['updateAt']= time();
                    if(!M("Inventory_warn")->add($batchData)){
                        $trans = false;
                    }
                }
                $dataList[] = array(
                    'batch' => date("Ymd",time()),
                    'cnt' => $cnt[$i],
                    'warn_batch' => $w,
                    'UID' => UID,
                    'createAt' => time(),
                    'BIN' => $BIN[$i]);
            }
            if($trans){
                $model->commit();
                M('Inventory_inlist')->addAll($dataList);
                $this->success('入库成功',U('Inventory/inprint',array('data'=>count($dataList))));
            }else{
                $model->rollback();
                $this->error('入库失败',U('Inventory/inventoryrealtime'));
            }
        }else{
            $map['status'] =1;
            $prolist = M("Material_product")->where($map)->select();
            $this->assign('product', json_encode($prolist) );
            $this->title = "原包装入库";
            $this->display();
        }
    }
    /**
     * 入库
     * @author James
     * 2016-01-15
     */
    public function inadd($BIN=null,$cnt=null,$warn_batch=null,$ybzBIN=null){
        if(IS_POST){
            $model = M('Inventory_warn');
            $trans = true;
            $length=count($BIN);
            if($length>1){
                $arr = array_flip(array_flip($BIN));
                if(count($arr)==1){
                    $this->error("检测到本次入库编码相同，自动终止！请分批处理！");
                }
            }
            for ($i = 0; $i < count($BIN); $i++) {
                if ($BIN[$i] == ""||$cnt[$i] == ""||$warn_batch[$i]==""||$ybzBIN[$i]=="") {
                    $this->error("入库商品信息不能为空");
                }
            }
            $model->startTrans();
            for ($i = 0; $i < count($BIN); $i++) {
                $batchMap['warn_batch'] = $warn_batch[$i];
                $batchMap['BIN'] = $BIN[$i];
                if($model->where($batchMap)->find()){
                    $inaddRes=$model->where($batchMap)->setInc('cnt',$cnt[$i]);
                    $model->where($batchMap)->setInc('initcnt',$cnt[$i]);
                    if(!$inaddRes){
                        $trans = false;
                    }else{
                        $model->where($batchMap)->save(array('updateAt'=>time()));
                    }
                }else{
                    $batchMap['BIN'] = $ybzBIN[$i];
                    $batchMap['warn_batch'] = $warn_batch[$i];
                    $ybzinfo = M('inventory_warn')->where($batchMap)->find();
                    $batchData['BIN']= $BIN[$i];
                    $batchData['warn_batch']= $warn_batch[$i];
                    $batchData['cnt']= $cnt[$i];
                    $batchData['initcnt']= $cnt[$i];
                    $batchData['pname']= get_name_by_id($BIN[$i],'Material_product','BIN','pname');
                    $batchData['have_days']= $ybzinfo['have_days'];
                    $batchData['createDay']= $ybzinfo['createDay'];
                    $batchData['per2_time']= $ybzinfo['per2_time'];
                    $batchData['per3_time']= $ybzinfo['per3_time'];
                    $batchData['createAt']= time();
                    $batchData['updateAt']= time();
                    $result2=M("Inventory_warn")->add($batchData);
                    if(!$result2){
                        $trans = false;
                    }
                }
                $dataList[] = array(
                    'batch' => date("Ymd",time()),
                    'cnt' => $cnt[$i],
                    'warn_batch' => $warn_batch[$i],
                    'UID' => UID,
                    'createAt' => time(),
                    'BIN' => $BIN[$i]);
            }
            if($trans){
                $model->commit();
                M('Inventory_inlist')->addAll($dataList);
                //$this->success('入库成功',U('Inventory/inprint',array('data'=>count($dataList))));
                $this->success('入库成功',U('Inventory/inlist'),3);//入库时不打印标签
            }else{
                $model->rollback();
                $this->error('入库失败',U('Inventory/inventoryrealtime'));
            }
        }else{
            $type = I('type');
            $type_arr = explode(".",$type);
            $type = $type_arr[0];
            $is_ybz = false;
            switch($type){
                case "zj":
                    $title="正价商品入库";
                    break;
                case "fl":
                    $title="福利商品入库";
                    break;
                case "zz":
                    $title="榨汁商品入库";
                    break;
                default:
                    break;
            }
            $this->title = $title;
            $this->type = $type;
            $this->is_ybz = $is_ybz;
            $this->display('inadd');
        }
    }
    public function inlist() {
        $where = "where 1 = 1 ";
        if(I('date')){
            $where.= "and batch like '%".I('date')."%'";
        }
        $Model = new Model();
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_inlist ".$where." group by batch  order by batch desc";
        $list1 = $Model->query($sql);
        $total = count($list1);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }

        $page = new \Think\Page($total, $listRows, $REQUEST);

        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();

        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_inlist ".$where." group by batch  order by batch desc limit $page->firstRow ,$page->listRows";
        $list1 = $Model->query($sql);
        $this->assign('_list', $list1);
        $this->title = '入库记录';
        $this->display();
    }
    public function indetail($batch="",$BIN="") {
        if($batch!=""){
            $map['batch'] = $batch;
        }
        if($BIN!=""){
            $map['BIN'] = $BIN;
        }
        $list = $this->lists('Inventory_inlist', $map,'createAt desc');
        $this->assign('_list', $list);
        $this->batch = $batch;
        $this->BIN = $BIN;
        $this->title = '入库明细';
        $this->display();
    }
    public function providerreject(){
        if(IS_POST){
            $model = M('Inventory_warn');
            $trans = true;
            $BIN_array = I('BIN');
            $cnt_array = I('cnt');
            $warn_batch_array = I('warn_batch');
            for ($i = 0; $i < count($BIN_array); $i++) {
                if ($BIN_array[$i] == ""||!($cnt_array[$i] <= 0)||$warn_batch_array[$i]=="" ){
                    $this->error("入库商品信息不能为空");
                }
            }
            $model->startTrans();
            for ($i = 0; $i < count($BIN_array); $i++){
                $batchMap['warn_batch'] = $warn_batch_array[$i];
                $batchMap['BIN'] = $BIN_array[$i];
                if($model->where($batchMap)->find()){
                    if(!$model->where($batchMap)->setInc('cnt',$cnt_array[$i])){
                        $trans = false;
                    }
                }
                $dataList[] = array(
                    'batch' => date("Ymd",time()),
                    'cnt' => $cnt_array[$i],
                    'warn_batch' => $warn_batch_array[$i],
                    'UID' => UID,
                    'createAt' => time(),
                    'BIN' => $BIN_array[$i]);
            }
            if($trans){
                $model->commit();
                M('Inventory_inlist')->addAll($dataList);
                $this->success('入库成功！',U('Inventory/inventoryrealtime'));
            }else{
                $model->rollback();
                $this->error('入库失败！',U('Inventory/inventoryrealtime'));
            }
        }else{
            $this->display();
        }
    }
    public function inFlowExport(){
        if ( empty($_REQUEST['batch']) ) {
            $this->error('请选择要操作的数据!');
        }
        $batchArr=$_REQUEST['batch'];
        $range="(";
        foreach($batchArr as $k=>$v){
                $range.= $k==0?"'".$v."'":",'".$v."'";
        }
        $range.=")";
        $sql="select a.BIN,b.classify,b.fruit_classify,b.pname,b.spec,a.cnt,a.warn_batch,c.username,a.batch
              from gr_inventory_inlist a,gr_material_product b,gr_ucenter_member c where a.batch in ".$range."
              and a.BIN=b.BIN and a.UID=c.id" ;
        $model=new Model();
        $data=$model->query($sql);
        if ($data){
//            $i = 0;
//            foreach($data as $key => $val){
//                $data[$i]['spec'] = get_name_by_id($val['BIN'],'Material_product','BIN','spec');
//                $data[$i]['classify'] = get_name_by_id($val['BIN'],'Material_product','BIN','classify');
//                $data[$i]['updateAt']=time_format($data[$i]['updateAt'],"Y-m-d");
//                $data[$i]['pd']=time_format($data[$i]['pd'],"Y-m-d");
//                $i++;
//            }
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "入库流水记录";

            $headArr = array("BIN","类别","水果类别","水果名","规格","数量","预警批次","操作人","操作时间");
            $title = "入库流水记录";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
    /**
     * 出库
     * @author James
     * 2016-01-14
     */
    public function outadd(){
        if(IS_POST){
            $cnt_array = I('cnt');
            $warnbatch_array = I('warn_batch');
            $BIN_array = I('BIN');
            $c = count($BIN_array);
            $model = M('Inventory_warn');
            $trans = true;
            for ($i = 0; $i < $c; $i++) {
                if ($cnt_array[$i] == "" || $warnbatch_array[$i] == "") {
                    $this->error("出库信息不完整");
                }
            }
            $model->startTrans();
            for ($i = 0; $i < $c; $i++) {
                $map['BIN'] = $BIN_array[$i];
                $map['warn_batch'] = $warnbatch_array[$i];
                if(!$model->where($map)->setDec('cnt',$cnt_array[$i])){
                    $trans = false;
                }else{
                    $model->where($map)->save(array('updateAt'=>time()));
                }
                $dataList[] = array(
                    'BIN'=>$BIN_array[$i],
                    'warn_batch'=>$warnbatch_array[$i],
                    'cnt'=>$cnt_array[$i],
                    'UID'=>UID,
                    'createAt'=>time(),
                    'batch' => date("Ymd",time())
                );
            }
            if($trans){
                $model->commit();
                M('Inventory_outlist')->addAll($dataList);
            }else{
                $model->rollback();
            }
            $this->success("操作成功",U('Inventory/inventoryrealtime'));
        }else{
            $this->title = '出库';
            $this->display();

        }
    }
    public function outlist() {
        $where = "where 1 = 1 ";
        if(I('date')){
            $where.= "and batch like '%".I('date')."%'";
        }
        $Model = new Model();
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_outlist  ".$where." group by batch order by batch desc";
        $list1 = $Model->query($sql);
        $total = count($list1);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);

        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_outlist  ".$where." group by batch order by batch desc limit $page->firstRow ,$page->listRows";
        $list1 = $Model->query($sql);
        $this->assign('_list', $list1);
        $this->title = '出库记录';
        $this->display();
    }
    public function outdetail($batch="",$BIN="") {
        if($batch!=""){
            $map['batch']=$batch;
        }
        if($BIN!=""){
            $map['BIN']=$BIN;
        }
        $list = $this->lists('Inventory_outlist', $map,'createAt desc');

        $this->assign('_list', $list);
        $this->title = '出库明细';
        $this->batch = $batch;
        $this->BIN = $BIN;
        $this->display();
    }
    /**
     * 报损
     */
    public function lossadd($lossNumber='',$applicant='',$applyTime='',$treasurer='',$operator='',$storeManager=''){
        if(IS_POST){
            $cnt_array = I('cnt');
            $unit_array = I('unit');
            $warnbatch_array = I('warn_batch');
            $BIN_array = I('BIN');
            $reason_array = I('reason');
            $loss_type_array = I('loss_type');
            $lossAt_array = I('lossAt');
            $c = count($BIN_array);
            for ($i = 0; $i < $c; $i++) {
                if ($BIN_array[$i]==""||$cnt_array[$i] == "" || $warnbatch_array[$i] == ""||$reason_array[$i]=="") {
                    $this->error("报损信息不完整");
                }
            }
            $rules = array(
                array('applyTime','require','请输入申请时间'),
                array('applicant','require','请输入申请人'),
            );
            $lossBatchModel=M('Loss_batch');
            if(!$lossBatchModel->validate($rules)->create()){
                $this->error($lossBatchModel->getError());
            }else{
                $lossBatchModel->create();
                $lossBatchModel->createAt=time();
                $lossBatchModel->UID=UID;
                $lossBatchModel->add();
            }
            for ($i = 0; $i < $c; $i++) {
                if($lossAt_array[$i]==""){
                    $lossAt_array[$i]=$applyTime;
                }
                $dataList[] = array(
                    'lossNumber'=>$lossNumber,
                    'BIN'=>$BIN_array[$i],
                    'warn_batch'=>$warnbatch_array[$i],
                    'cnt'=>$cnt_array[$i],
                    'unit'=>$unit_array[$i],
                    'reason'=>$reason_array[$i],
                    'loss_type'=>$loss_type_array[$i],
                    'lossAt'=>strtotime($lossAt_array[$i]),
                    'createAt'=>time(),
                );
            }
            M('Inventory_losslist')->addAll($dataList);
            $this->success("操作成功",U('Inventory/lossadd'));
        }else{
            $this->lossNumber=time();
            $this->title = '报损';
            $this->display();
        }
    }
    public function losslist() {
        $list1=$this->lists('Loss_batch');
        $this->assign('_list', $list1);
        $this->title = '报损记录';
        $this->display();
    }
    public function lossdetail() {
        $lossNumber = I('lossNumber');
        if($lossNumber){
            $map['lossNumber'] = $lossNumber;
        }
        $map['status']  =   1;
        $list = $this->lists('Inventory_losslist', $map,'createAt desc');
        $this->assign('_list', $list);
        $this->title = '报损明细';
        $this->display();
    }
    public function lossoldexport($classify="",$start="",$end="",$BIN=""){
        if(IS_POST){
            $sql="select a.BIN,a.warn_batch,b.pname,b.spec,a.cnt,a.reason,date_format(FROM_UNIXTIME(a.createAt),'%Y-%m-%d %H:%i:%s') from gr_inventory_losslist a,gr_material_product b where a.BIN=b.BIN ";
            if($classify!=""){
                $sql.=" and a.BIN like '".$classify."%'";
            }
            if($start!=""){
                $startTimeStamp=strtotime($start);
                $sql.=" and a.createAt>".$startTimeStamp."";
            }
            if($end!=""){
                $endTimeStamp=strtotime($end);
                $sql.=" and a.createAt<".$endTimeStamp."";
            }
            if($BIN!=""){
                $sql.=" and a.BIN like ".$BIN."%'";
            }
            $model=new Model();
            $list=$model->query($sql);
            if ($list){
//                $i = 0;
//                foreach($list as $key => $val){
//                    $data[$i]['pname'] = get_name_by_id($val['BIN'],'Material_product','BIN','pname');
//                    $data[$i]['spec'] = get_name_by_id($val['BIN'],'Material_product','BIN','spec');
//                    $i++;
//                }
                //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
                import("Org.Util.PHPExcel");
                import("Org.Util.PHPExcel.Writer.Excel5");
                import("Org.Util.PHPExcel.IOFactory.php");

                $filename = "output_order_excel";

                $headArr = array("BIN","批次", "商品名称","规格","数量","理由","创建时间");

                $title = "报损流水数据";
                $this->getExcel($filename, $headArr, $list, $title);
            }else{
                $this->error("没有可导出的数据！");
            }
        }else{
            if($classify!=""){
                $map['BIN']=array('like',$classify.'%');
                $this->classify=$classify;
            }
            if($start!=""){
                $startTimeStamp=strtotime($start);
                $map['createAt']=array('egt',$startTimeStamp);
                $this->start=$start;
            }
            if($end!=""){
                $endTimeStamp=strtotime($end);
                $map['createAt']=array('elt',$endTimeStamp);
                $this->end=$end;
            }
            if($start!=""&&$end!=""){
                $endTimeStamp=strtotime($end);
                $startTimeStamp=strtotime($start);
                $map['createAt']=array('between',array($startTimeStamp,$endTimeStamp));
            }
            if($BIN!=""){
                $map['BIN']=array('like',$BIN."%'");
                $this->BIN=$BIN;
            }
            if($map!=null){
                $losslist=$this->lists('inventory_losslist',$map);
                $this->_list=$losslist;
            }
            $classifyList=M('Material_classify')->where(array('status'=>1))->select();
            $this->_classify=$classifyList;
            $this->title="报损历史数据";
            $this->display();
        }
    }
    /***
     * 盘点
     */
    public function checkinventory(){
        if(IS_POST){
            $checkcnt_array = I('check_cnt');
            $warnbatch_array = I('warn_batch');
            $BIN_array = I('BIN');
            $reason_array = I('reason');
            $inventory_array = I('inventory');
            $c = count($BIN_array);
            $model = M('Inventory_warn');
            $trans = true;
            for ($i = 0; $i < $c; $i++) {
                if ($checkcnt_array[$i] == "" || $warnbatch_array[$i] == ""||$BIN_array[$i] == ""||$inventory_array[$i] == "") {
                    $this->error("盘点信息不完整");
                }
            }
            $model->startTrans();
            for ($i = 0; $i < $c; $i++) {
                $map['BIN'] = $BIN_array[$i];
                $map['warn_batch'] = $warnbatch_array[$i];
                $data['cnt'] = $checkcnt_array[$i];
                $data['checkAt'] = time();
                if($model->where($map)->save($data)===false){
                    $trans= false;
                }
                $dataList[] = array(
                    'BIN'=>$BIN_array[$i],
                    'warn_batch'=>$warnbatch_array[$i],
                    'before_cnt'=>$inventory_array[$i],
                    'checkcnt'=>$checkcnt_array[$i],
                    'reason'=>$reason_array[$i],
                    'UID'=>UID,
                    'createAt'=>time(),
                    'batch' => date("Ymd",time())
                );
            }
            if($trans){
                $model->commit();
                M('Inventory_check')->addAll($dataList);
            }else{
                $model->rollback();
            }
            $this->success("操作成功");
        }else{
            $this->title = '盘点';
            $this->display();

        }
    }
    public function checklist() {
        $where = "where 1 = 1 ";
        if(I('date')){
            $where.= "and batch like '%".I('date')."%'";
        }
        $Model = new Model();
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_check  ".$where." group by batch order by batch desc";
        $list1 = $Model->query($sql);
        $total = count($list1);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }

        $page = new \Think\Page($total, $listRows, $REQUEST);

        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $sql = "select batch ,count(BIN) as count1  from gr_inventory_check  ".$where." group by batch order by batch desc limit $page->firstRow ,$page->listRows";
        $list1 = $Model->query($sql);
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $this->assign('_list', $list1);
        $this->title = '盘点记录';
        $this->display();
    }
    public function checkdetail() {
        $batch = I('batch');
        if($batch){
            $map['batch'] = array('like', '%' . (string) $batch . '%');
        }

        $map['status']  =   1;

        $list = $this->lists('Inventory_check', $map,'createAt desc');

        $this->assign('_list', $list);
        $this->title = '盘点明细';
        $this->display();
    }
    /**
     * 实时库存导出
     * @author James
     * 2016-02-18
     */
    public function kcExport() {
        $where = "";
        if(I('BIN')!=""){
            $where.="and BIN like '%".I('BIN')."%' ";
//            $map['BIN'] = array('like','%'.I('BIN').'%');
        }
        if(I('pname')!=""){
            $where.="and pname like '%".I('pname')."%' ";
//            $map['pname'] = array('like','%'.I('pname').'%');
        }
        if(I('classify')!=""&&I('BIN')==""){
            $where.="and BIN like '".I('classify')."%' ";
//            $map['BIN'] = array('like',I('classify').'%');
        }

        $sql = "select a.BIN,a.cnt,a.pname,(select b.updateAt from gr_inventory_warn b where a.BIN=b.BIN ORDER by b.checkAt DESC limit 1) as updateAt,(select b.checkAt from gr_inventory_warn b where a.BIN=b.BIN ORDER by b.checkAt DESC limit 1) as pd from gr_vinventory a where 1=1 ".$where." ORDER BY a.cnt desc";
        $Model = new Model();
        $data = $Model->query($sql);
        if ($data){
            add_erp_log('Inventory','vinventory','库存表','export','导出库存表');
            $i = 0;
            foreach($data as $key => $val){
                $data[$i]['spec'] = get_name_by_id($val['BIN'],'Material_product','BIN','spec');
                $data[$i]['classify'] = get_name_by_id($val['BIN'],'Material_product','BIN','classify');
                $data[$i]['updateAt']=time_format($data[$i]['updateAt'],"Y-m-d");
                $data[$i]['pd']=time_format($data[$i]['pd'],"Y-m-d");
                $i++;
            }
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";

            $headArr = array("BIN","数量", "商品名称","最近盘点","最近修改","规格","货别");

            $title = "实时库存列表";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
    private function getExcel($fileName, $headArr, $data, $title) {
        //对数据进行检验
        if (empty($data) || !is_array($data)) {
            //die("data must be a array");
        }
        //检查文件名
        if (empty($fileName)) {
            exit;
        }
        // H:i:s
        $date = date("Y_m_d_H_i_s", time());
        //$date = date("Y_m_d",time());
        $fileName .= "_{$date}.xls";

        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

        //第一列设置报表时间范围
        $key = ord("A");
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $title);


        //第二列设置报表列头
        $key = ord("A");
        foreach ($headArr as $v) {
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '2', $v);
            $key += 1;
        }

        $column = 3;
        $objActSheet = $objPHPExcel->getActiveSheet();
        foreach ($data as $key => $rows) { //行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) {// 列写入
                $j = chr($span);
                $objActSheet->setCellValue($j . $column, $value);
                $objActSheet->getColumnDimension('a')->setWidth(10);
                $objActSheet->getColumnDimension('b')->setWidth(10);
                $objActSheet->getColumnDimension('c')->setWidth(20);
                if (count($headArr) == 12){
                    $objActSheet->getColumnDimension('d')->setWidth(20);
                    $objActSheet->getColumnDimension('h')->setWidth(20);
                    $objActSheet->getColumnDimension('i')->setWidth(20);
                    $objActSheet->getColumnDimension('j')->setWidth(30);
                    $objActSheet->getColumnDimension('l')->setWidth(100);
                }else{
                    $objActSheet->getColumnDimension('g')->setWidth(20);
                    $objActSheet->getColumnDimension('h')->setWidth(20);
                    $objActSheet->getColumnDimension('i')->setWidth(30);
                    $objActSheet->getColumnDimension('j')->setWidth(30);
                    $objActSheet->getColumnDimension('k')->setWidth(100);
                }
                $span++;
            }
            $column++;
        }

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
    /**
     * 库存预警
     */
    public function warn(){
        set_time_limit(0);
        $today = date('Ymd',time());
        $status = 1;
        if(I('status')!=""){
            $status = I('status');
        }
        if(I('zxstatus')!=""){
            $map['zxstatus'] = I('zxstatus');
        }
        if(I('warn_batch')){
            $map['warn_batch'] = array("like","%".I('warn_batch')."%");
        }
        if(I('pname')){
            $map['pname'] = array("like","%".I('pname')."%");
        }
        if(I('cnt')!=""){
            $map['cnt']=0;
        }
        if(I('BIN')){
            $map['BIN'] = array("like","%".I('BIN')."%");
        }
        if(I('warn_status')){
            switch (I('warn_status')){
                case 1:
                    $map['per2_time'] =array('egt',$today);
                    break;
                case 2:
                    $map['per2_time'] =array('lt',$today);
                    $map['per3_time'] =array('egt',$today);
                    break;
                case 3:
                    $map['per3_time'] =array('lt',$today);
                    break;
                default:
                    break;
            }
        }
        $map['status'] = $status;
        $list = $this->lists("Inventory_warn",$map);
        list_bin_array($list);
        /***
         * 滞销预警功能
         * 已存放天数 a
         * 销售期总天数 b(净销售期-入库时间)
         **注：车厘子20天销售期 入库时存放3天 净销售期 为 17
         *某批次销量 s (初始库存-库存)
         * 原始库存 i
         * d(时间比例 d = a/b)
         * p(销售比例 p = s/i)
         * if((p-d)>=10%) 不会滞销 else 滞销
         * if(d < 0.5 ) 时间未过半 不滞销
         * 销量大于90%，不滞销
         * */
        foreach($list as $k=>$v){
            $per2 = strtotime($v['per2_time']);
            $createDay = strtotime($v['createDay']);
            $t = strtotime(date("Y-m-d 00:00:00",time()));
            $allday = ($per2-$createDay)/(24*3600);
            $passday = ($t-$createDay)/(24*3600);
            $sell_num = $v['initcnt']-$v['cnt'];
            $initcnt = $v['cnt'];
            if((($sell_num/$initcnt)-($passday/$allday))>=0.1){
                $list[$k]['zx'] = -1;
            }else{
                $list[$k]['zx'] = 1;
            }
            if(($passday/$allday)<0.5){
                $list[$k]['zx'] = -1;
            }
            if(($sell_num/$initcnt)>=0.9){
                $list[$k]['zx'] = -1;
            }
            if(time()>$per2){
                $list[$k]['zx'] = -1;
            }
            if($v['cnt']==0){
                $list[$k]['zx'] = -1;
            }
            $v['zxstatus'] =  $list[$k]['zx'];
            M('inventory_warn')->save($v);
        }
        $this->today = $today;
        $this->pname = I('pname');
        $this->warn_status = I('warn_status');
        $this->zxstatus = I('zxstatus');
        $this->status = $status;
        $this->title = "库存预警";
        $this->assign("_list",$list);
        $this->display();
    }
    public function clear(){
        $map['cnt'] = array('ELT',0);
        $data['status'] = -1;
        M('inventory_warn')->where($map)->save($data);
        $this->success("部分批次已禁用，你可以在禁用列表找到它");
    }
    public function newcntwarn(){
        if(IS_POST){
            $model = M('Material_product');
            $rules = array(
                array('cnt_low', '/[0-9]+/','请输入纯数字' , 1 , 'regex' ,1),
                array('cnt_poor', '/[0-9]+/','请输入纯数字' , 1 , 'regex' ,1),
                array('cnt_much', '/[0-9]+/','请输入纯数字' , 1 , 'regex' ,1),
            );
            if(!$model->validate($rules)->create()){
                $this->error(M('Material_product')->getError());
            }else{
                $map['BIN'] = I('BIN');
                $data['cnt_low'] = I('cnt_low');
                $data['cnt_poor'] = I('cnt_poor');
                $data['cnt_much'] = I('cnt_much');
                if($model->where($map)->save($data)){
                    $this->success("设置成功");
                }else{
                    $this->error("设置失败");
                }
            }
        }else{
            if(I('BIN')==""){
                $this->error("信息不完全请重新点击链接",U('inventoryrealtime'));
                return false;
            }
            $this->BIN = I('BIN');
            $this->display();
        }

    }
    public function cntwarn(){
        $status = "";
        $promap['cnt_poor']=array('gt',0);
        $BIN_arr=M("Material_product")->where($promap)->getField('BIN',true);
        $range="(";
        foreach($BIN_arr as $k=>$v){
            $range.=($k+1)==count($BIN_arr)? $v:$v.",";
        }
        $range.=")";
        $model = M('vinventory');
        $sql= "select * from gr_vinventory where 1=1 and cnt>0";
        if(I('BIN')!==""){
            $sql.=" and BIN like '%".I('BIN')."%'";
//            $map['BIN'] = array('like','%'.I('BIN').'%');
        }else{
            $sql.=" and BIN in $range";
        }

        if(I('pname')!==""){
            $sql.=" and pname like '%".I('pname')."%'";
//            $map['pname'] = array('like','%'.I('pname').'%');
        }
        if(I('status')!==""){
            $status = I('status');
        }
        $res = $model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $classify = M('Material_classify')->where(array('status'=>1))->select();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow ,$page->listRows";
        $res = $model->query($sql);
        list_bin_array($res);
        get_cnt_warn($res,$status);
        $this->assign('_list',$res);
        $this->assign('_classify',$classify);
        $this->status = $status;
        $this->title = "库存预警";
        $this->display();
    }
    public function searchcntwarn($status="",$pname="",$BIN=""){
        $model = M('vinventory');
        $sql="select a.*,b.cnt_low,b.cnt_poor,b.cnt_much from gr_vinventory a ,gr_material_product b where a.cnt>0 and b.cnt_poor>0";
        switch($status){
            case '1':
                $sql.=" and a.cnt<=b.cnt_low";
                break;
            case '2':
                $sql.=" and a.cnt<=b.cnt_poor and a.cnt>b.cnt_low";
                break;
            case '3':
                $sql.=" and a.cnt<=b.cnt_much and a.cnt>b.cnt_poor";
                break;
            case '4':
                $sql.=" and  a.cnt>b.cnt_much";
                break;
            default:
                break;
        }
        if($pname!=""){
            $sql.=" and a.pname like '%".$pname."%'";
        }
        if($BIN!=""){
            $sql.=" and a.BIN like '%".$BIN."%'";
        }
        $sql.=" and a.BIN=b.BIN ";
        $res = $model->query($sql);
        $total = count($res);
        if (isset($REQUEST['r'])) {
            $listRows = (int) $REQUEST['r'];
        } else {
            $listRows = C('LIST_ROWS') > 0 ? C('LIST_ROWS') : 10;
        }
        $page = new \Think\Page($total, $listRows, $REQUEST);
        if ($total > $listRows) {
            $page->setConfig('theme', '%FIRST% %UP_PAGE% %LINK_PAGE% %DOWN_PAGE% %END% %HEADER%');
        }
        $p = $page->show();
        $classify = M('Material_classify')->where(array('status'=>1))->select();
        $this->assign('_page', $p ? $p : '');
        $this->assign('_total', $total);
        $sql.=" limit $page->firstRow ,$page->listRows";
        $res = $model->query($sql);
        $this->assign('_list',$res);
        $this->assign('_classify',$classify);
        $this->status = $status;
        $this->pname = $pname;
        $this->BIN = $BIN;
        $this->title = "库存预警";
        $this->display('searchcntwarn');
    }
    public function add_warn_days(){

        $id = I('id');
        $days = I('days');
        $res = M('Inventory_warn')->where(array('id'=>$id))->find();
        $data['per2_time'] = date("Ymd",strtotime('+'.$days.' day',strtotime($res['per2_time'])));
        $data['per3_time'] = date("Ymd",strtotime('+'.$days.' day',strtotime($res['per3_time'])));
        if(M('Inventory_warn')->where(array('id'=>$id))->save($data)){
            add_erp_log('Inventory','inventory_warn',$res['BIN'],'update','商品'.$res['BIN'].'延长天数'.$days);
            $this->success('修改成功');
        }

    }
    /**
     * 手机端隐藏部分商品
     * @param $BIN
     */
    public function hide($BIN){
        $model=M('inventory_hide');
        $data['BIN']=$BIN;
        $data['createAt']=time();
        $res=$model->add($data);
        if($res){
            $this->success('隐藏成功，你可以点击展示全部找到它');
        }else{
            $this->error('隐藏失败');
        }
    }
    /**
     * 手机端显示商品
     */
    public function show($BIN){
        $model=M('inventory_hide');
        $map['BIN']=$BIN;
        $res=$model->where($map)->delete();
        if($res){
            $this->success('显示成功');
        }else{
            $this->error('显示失败');
        }
    }
    public function warnExport() {
        $today = date('Ymd',time());
        $where = "";
        if(I('status')==0){
            $where.=" and status = 0";
        }else{
            $where.=" and status = 1 ";
        }
        if(I('warn_batch')){
            $where.=" and warn_batch like '%".I('warn_batch')."%'";
        }
        if(I('pname')){
            $where.=" and pname like '%".I('pname')."%'";
        }
        if(I('BIN')){
            $where.=" and BIN like '%".I('BIN')."%'";
        }
        if(I('warn_status')){
            switch (I('warn_status')){
                case 1:
                    $where.=" and per2_time >= ".$today."";
                    break;
                case 2:
                    $where.=" and per2_time >= ".$today." and per2_time < ".$today."";
                    break;
                case 3:
                    $where.=" and per2_time < ".$today."";
                    break;
                default:
                    break;
            }
        }

        $sql = "select BIN,warn_batch,cnt, case when".
          " per2_time > ".$today." then '销售'".
         "when per3_time < ".$today." then '处理'".
         "else '榨汁' end, per2_time,per3_time from gr_inventory_warn  where 1=1 ".$where."";
        $Model = new Model();
        $data = $Model->query($sql);
        if ($data){
            add_erp_log('Inventory','inventory_warn','预警表','export','导出预警表');
            $i = 0;
             foreach($data as $key => $val){
                 array_splice($data[$i], 1,0,get_name_by_id($val['BIN'],'Material_product','BIN','pname'));
                 array_splice($data[$i], 2,0,get_name_by_id($val['BIN'],'Material_product','BIN','spec'));
                $i++;
             }
            //导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
            import("Org.Util.PHPExcel");
            import("Org.Util.PHPExcel.Writer.Excel5");
            import("Org.Util.PHPExcel.IOFactory.php");

            $filename = "output_order_excel";

            $headArr = array("编码","商品名","规格","预警批次", "数量","预警状态","预估榨汁期","预估处理器");
            $title = "实时库存列表";
            $this->getExcel($filename, $headArr, $data, $title);
        }else{
            $this->error("没有可导出的数据！");
        }
    }
    public function inprint(){
        $arr = [];
        if(I('data')!=""){
            $kinds = intval(I('data'));
            $plist = M('inventory_inlist')->limit($kinds)->order('createAt desc')->select();
            for($i=0;$i<$kinds;$i++){
                $res = M('inventory_inlist')->limit($i,1)->order('createAt desc')->select();
                $cnt = $res[0]['cnt'];
                $res[0]['warn_batch'] = gr_encode($res[0]['warn_batch']);
                for($j = 1;$j<=$cnt;$j++){
                    $arr[]=$res[0];
                }
            }
        }else if(I('id')!=""&&I('num')>0){
            $plist = M('inventory_inlist')->where(array('id'=>I('id')))->select();
            $res = $plist;
            for($j = 1;$j<=I('num');$j++){
                $res[0]['warn_batch'] = gr_encode($res[0]['warn_batch']);
                $arr[]=$res[0];
            }
        }else if(count(I())>0){
            $plist = M('inventory_inlist')->where(array('id'=>array('in',I())))->select();
            for($i=0;$i<count(I());$i++){
                $res = M('inventory_inlist')->where(array('id'=>I()[$i]))->select();
                $cnt = $res[0]['cnt'];
                $res[0]['warn_batch'] = gr_encode($res[0]['warn_batch']);
                for($j = 1;$j<=$cnt;$j++){
                    $arr[]=$res[0];
                }
            }
        }
        $this->plist = $plist;
        $this->assign("lists",$arr);
        $this->display();
    }
    public function extraprint($num = null){
        $arr = $_REQUEST['id'];
        if($num==0&&$arr!=""){
            $this->success('',U('inventory/inprint',$arr));
        }else if($arr!=""){
            $this->success('',U('inventory/inprint',array('num'=>$num,'id'=>$arr[0])));
        }else{
            $this->error('未选择批次');
        }
    }
    public function iodetail($BIN="",$warn_batch=""){
        $map['BIN'] = $BIN;
        $map['warn_batch'] = $warn_batch;
        $inlist=M('inventory_inlist')->where($map)->getField('createAt,BIN,warn_batch,cnt,UID,act',true);
        $outlist=M('inventory_outlist')->where($map)->getField('createAt,BIN,warn_batch,cnt,UID,act',true);
        $losslist=M('inventory_losslist')->where($map)->getField('createAt,BIN,warn_batch,cnt,UID,act',true);
        foreach($inlist as $k=>$v){
            $outlist[$k]=$v;
        }
        foreach($losslist as $k=>$v){
            $outlist[$k]=$v;
        }
         krsort($outlist);
        $this->assign("_list",$outlist);
        $this->display();
    }
    /**
     * 下面是angular接
     */
    public function ajaxgetybzlist($BIN){
        $BIN = substr($BIN,1,4);
        $map['BIN'] =array('like','1'.$BIN.'%');
        $map['status'] =1;
        $res = M('inventory_warn')->where($map)->order('warn_batch desc')->select();
        $this->ajaxReturn($res);
    }
    public function ajaxgetybzBINlist($BIN){
        $BIN = substr($BIN,1,4);
        $map['BIN'] =array('like','1'.$BIN.'%');
        $map['status'] =1;
        $res = M('inventory_warn')->where($map)->getField('BIN',true);
        $res = array_flip(array_flip($res));
        $promap['BIN'] = array('in',$res);
        $list = M('Material_product')->where($promap)->select();
        $this->ajaxReturn($list);
    }
    public function ajaxgetbatchlist($BIN="",$cnt=0){
        $map['status'] =1;
        $map['cnt'] =array('gt',$cnt);
        if($BIN!="") {
            $map['BIN'] = $BIN;
        }
        $res = M('inventory_warn')->where($map)->order('warn_batch desc')->select();
        $this->ajaxReturn($res);
    }
    public function ajaxgetproductlist($type=""){
        switch($type){
            case "ybz":
                $map['BIN'] = array('like','1%');
                break;
            case "zj":
                $map['BIN'] = array('like','2%');
                break;
            case "fl":
                $map['BIN'] = array('like','3%');
                break;
            case "zz":
                $map['BIN'] = array('like','4%');
                break;
        }
        $map['status'] = 1;
        $prolist = M("Material_product")->where($map)->select();
        $this->ajaxReturn($prolist);
    }
    public function ajaxgetinventory($type='all'){
        switch($type){
            case 'all':
                $map=array();
                break;
            case 'ybz':
                $map['BIN']=array("like",'1%');
                break;
        }
//        $map['cnt']  =   array('gt',0);
        $prolist = M("Vinventory")->where($map)->getField('BIN',true);
        $map2['BIN']=array('in',$prolist);
        $inventory_warn = M("Material_product")->where($map2)->select();
        $this->ajaxReturn($inventory_warn);
    }
    public function ajaxcheckinventorylist(){
        $prolist = M('Vinventory')->getField('BIN',true);
        $map2['BIN']=array('in',$prolist);
        $map2['status']=1;
        $res = M("Material_product")->where($map2)->select();
        $this->ajaxReturn($res);
    }
    public function ajaxcheckbatchlist($BIN=""){
        $map['status'] =1;
        if($BIN!="") {
            $map['BIN'] = $BIN;
        }
        $res = M('inventory_warn')->where($map)->select();
        $this->ajaxReturn($res);
    }
    public function ajaxGetLossReason(){
        $res=C('Loss_Reason');
        $this->ajaxReturn($res);
    }
}
